import React, { useState, useEffect } from 'react';
import { Button, Table, Input, Space, Modal, Form, Select, message } from 'antd';
import type { TableColumnsType } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import styles from './index.less';
import { getUser, getRole, editUser, addUser, deleteUser } from '@/api/services';

interface DataType {
    key: React.Key;
    name: string;
    age: string;
    address: string;
    address2: string;
    person: string;
}



const RoleMangement: React.FC = () => {
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    const [search, setSearch] = useState<string>('');
    const [searchValue, setSearchValue] = useState<string>('');
    const [page, setPage] = useState(1);
    const [total, setTotal] = useState(0);
    const [data, setData] = useState([]);
    // const [editId, setEditId] = useState<any>('');
    const [modalOpen, setModalOpen] = useState<boolean>(false);
    const [editModalOpen, setEditModalOpen] = useState(false);
    const [form] = Form.useForm();
    const [form1] = Form.useForm();
    const [roles, setRoles] = useState<any>([]);
    const [userId, setUserId] = useState('');


    const hasSelected = selectedRowKeys.length > 0;

    const getUserList = () => {
        getUser({
            page: page,
            size: 10,
            name: searchValue ? searchValue : ''
        }).then((res: any) => {
            if(res.status == 200){
                const newData = res.results.map((item: any) => {
                    return { ...item, key: item.user_id };
                });
                setData(newData);
                setTotal(res.length);
            }
            
        })
    }

    useEffect(() => {
        getUserList();
    }, [page, searchValue]);

    useEffect(() => {
        getRole({ page: 1, size: 10 }).then((res: any) => {
            if(res.status == 200){
                console.log(res);
                const options = res.results.map((user: any) => ({
                    value: user.role_desc,
                    label: user.role_desc,
                }));
                setRoles(options);
            }
            
        })
    }, [])

    const handleChange = (e: any) => {
        setSearch(e.target.value);
    };
    const onSearch = () => {
        setSearchValue(search);
    }

    //新增用户
    const addUserList = async () => {
        const validate = await form.validateFields();
        addUser({
            userName: validate.user_name,
            // pwd: validate.user_pwd,
            userNumber: validate.user_number,
            roleName: validate.roleName,
        }).then((res: any) => {
            if(res.status == 200){
                console.log(res);
                message.success('新增成功');
                setModalOpen(false);
                getUserList();
            }
            
        })
    }

    //编辑用户
    const editUserList = async () => {
        const validate = await form1.validateFields();
        console.log('111', validate);
        editUser({
            userId: userId,
            userName: validate.user_name,
            pwd: validate.user_pwd,
            number: validate.user_number,
            roleName: validate.roleName,
        }).then((res: any) => {
            if(res.status == 200){
                console.log(res);
                message.success('编辑成功');
                getUserList();
                setEditModalOpen(false);
            }
            
        })
    }

    //删除用户
    const delUserList = (id: any) => {
        console.log('id', id);
        deleteUser({
            userId: id
        }).then((res: any) => {
            if(res.status == 200){
                console.log(res);
                message.success('删除成功');
                getUserList();
            }
            
        })
    }

    const columns: TableColumnsType<DataType> = [
        {
            title: '用户头像',
            dataIndex: 'user_avatar',
            render: (text: any, record: any) => {
                return (
                    <img src={record.user_avatar} style={{ width: '50px', height: '50px', borderRadius: '25px' }} />
                )
            }
        },
        {
            title: '用户姓名',
            dataIndex: 'user_name',
        },
        {
            title: '用户角色',
            dataIndex: 'roleName'
        },
        {
            title: '用户电话',
            dataIndex: 'user_number',
        },
        {
            title: 'Action',
            dataIndex: '',
            key: 'x',
            render: (text: any, record: any) =>
                <Space size="middle">
                    <a
                        onClick={() => {
                            setEditModalOpen(true);
                            setUserId(record.user_id);
                            form1.setFieldsValue(record);
                            console.log('user', record);
                        }}
                    >
                        编辑
                    </a>
                    <a onClick={() => { delUserList(record.user_id) }}>删除</a>
                </Space>
        },
    ];

    const paginationConfig = {
        total: total,
        onChange: (page: number, pageSize?: number) => {
            setPage(page);
        },
        showTotal: (total: number, range: [number, number]) => `共 ${total} 条数据`,
    }

    const ModalFooter = (
        <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
            <Button
                type="primary"
                style={{ marginRight: 16, borderRadius: 6 }}
                onClick={addUserList}
            >
                确定
            </Button>
            <Button
                style={{ marginRight: 16, borderRadius: 6 }}
                onClick={() => { setModalOpen(false) }}
            >
                取消
            </Button>
        </div>
    )

    //编辑客户footer
    const EditModalFooter = (
        <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
            <Button
                type="primary"
                style={{ marginRight: 16, borderRadius: 6 }}
                onClick={editUserList}
            >
                确定
            </Button>
            <Button
                style={{ marginRight: 16, borderRadius: 6 }}
                onClick={() => { setEditModalOpen(false) }}
            >
                取消
            </Button>
        </div>
    )

    return (
        <div className={styles.orderContainer}>

            <div className={styles.header}>
                <Input
                    value={search}
                    onChange={handleChange}
                    style={{ width: 240 }}
                    allowClear
                    placeholder="搜索用户"
                    className={styles.input}
                    suffix={<SearchOutlined onClick={onSearch} />}
                    onPressEnter={onSearch}
                />

                <Button type="primary" style={{ marginRight: 20 }}
                    onClick={() => {
                        setModalOpen(true);
                        form.resetFields();
                    }}
                >新增用户</Button>
                {/* <Button type="primary" danger>批量删除</Button> */}
            </div>
            <Table columns={columns} dataSource={data} pagination={paginationConfig} />
            {modalOpen &&
                <Modal
                    open={modalOpen}
                    title="新增用户"
                    onCancel={() => { setModalOpen(false) }}
                    footer={ModalFooter}
                >
                    <Form
                        form={form}
                        labelCol={{ span: 4 }}
                        wrapperCol={{ span: 14 }}
                    >
                        <Form.Item label="用户姓名" name="user_name">
                            <Input />
                        </Form.Item>
                        {/* <Form.Item label="用户密码" name="user_pwd">
                            <Input />
                        </Form.Item> */}
                        <Form.Item label="用户电话" name="user_number">
                            <Input />
                        </Form.Item>
                        <Form.Item label="用户角色" name="roleName">
                            <Select options={roles} />
                        </Form.Item>
                    </Form>
                </Modal>
            }
            {/* 编辑客户 */}
            {editModalOpen &&
                <Modal
                    open={editModalOpen}
                    title="编辑客户"
                    onCancel={() => { setEditModalOpen(false) }}
                    footer={EditModalFooter}
                >
                    <Form form={form1}
                        labelCol={{ span: 6 }}
                        wrapperCol={{ span: 18 }}
                    >
                        <Form.Item label="用户姓名" name="user_name">
                            <Input />
                        </Form.Item>
                        <Form.Item label="用户密码" name="user_pwd">
                            <Input />
                        </Form.Item>
                        <Form.Item label="用户电话" name="user_number">
                            <Input />
                        </Form.Item>
                        <Form.Item label="用户角色" name="roleName">
                            <Select options={roles} />
                        </Form.Item>
                    </Form>
                </Modal>
            }
        </div>
    );
};

export default RoleMangement;